package com.rsn.genxdgrid.jms;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created with IntelliJ IDEA.
 * User: Ravdeep
 * Date: 22/2/14
 * Time: 12:04 AM
 * To change this template use File | Settings | File Templates.
 */
public class Consumer {
    // URL of the JMS server
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the queue we will receive messages from
    private static String subject = "TestQ";

    public static void main(String[] args) throws JMSException, InterruptedException {
        System.out.println("********  Started Listening To TestQ *******");
        while(true){
            getMessage();
            Thread.sleep(5000);
        }

    }

    private static void getMessage() throws JMSException {

        ConnectionFactory connectionFactory
                = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();


        Session session = connection.createSession(false,
                Session.AUTO_ACKNOWLEDGE);


        Destination destination = session.createQueue(subject);


        MessageConsumer consumer = session.createConsumer(destination);

        Message message = consumer.receive();


        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message '"
                    + textMessage.getText() + "'");
        }
        connection.close();
    }
}